package model

import (
	"bytes"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"qihuang/config"
	"qihuang/helper"
	"qihuang/loger"
	"time"
)

// DB 数据库链接单例
var DB *gorm.DB

// Database 在中间件中初始化mysql链接
func Database(connString string) {
	db, err := gorm.Open("mysql", connString)
	db.LogMode(true)
	// Error
	if err != nil {
		loger.Loger.Panic("连接数据库不成功", err)
	}
	//设置连接池
	//空闲
	db.DB().SetMaxIdleConns(50)
	//打开
	db.DB().SetMaxOpenConns(100)
	//超时
	db.DB().SetConnMaxLifetime(time.Second * 30)

	DB = db

	//Migration()
}

func Init() {
	appDir := helper.GetAppDir()
	config.Default(appDir + "/config.ini")
	dbUser := config.Configs.DBUser
	dbPwd := config.Configs.DBPass
	dbHost := config.Configs.DBHost
	dbName := config.Configs.DBName
	dbPort := config.Configs.DBPort
	var bt bytes.Buffer
	// 向bt中写入字符串
	bt.WriteString(dbUser)
	bt.WriteString(":")
	bt.WriteString(dbPwd)
	bt.WriteString("@tcp(")
	bt.WriteString(dbHost)
	bt.WriteString(":")
	bt.WriteString(dbPort)
	bt.WriteString(")/")
	bt.WriteString(dbName)
	bt.WriteString("?charset=utf8mb4&parseTime=True&loc=Local")
	connStr := bt.String()
	Database(connStr)
}